package com.tang.shardingjdbcdemo.algorithm;

import com.google.common.collect.Range;
import com.tang.shardingjdbcdemo.utils.DateUtils;
import lombok.SneakyThrows;
import org.apache.shardingsphere.api.sharding.standard.RangeShardingAlgorithm;
import org.apache.shardingsphere.api.sharding.standard.RangeShardingValue;

import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeFormatterBuilder;
import java.time.temporal.ChronoField;
import java.util.Collection;
import java.util.Date;
import java.util.LinkedHashSet;
import java.util.List;

public class TimeRangeShardingAlgorithm implements RangeShardingAlgorithm<String> {

    @SneakyThrows
    @Override
    public Collection<String> doSharding(Collection<String> availableTargetNames, RangeShardingValue<String> shardingValue) {
        Collection<String> result = new LinkedHashSet<String>();
        //逻辑表名
        String logicTableName = shardingValue.getLogicTableName();
        Range<String> shardingKey = shardingValue.getValueRange();
        //范围查询最小值 yyyy-MM-dd HH:mm:ss
        String startShardingKey = shardingKey.lowerEndpoint();
        //范围查询最大值 yyyy-MM-dd HH:mm:ss
        String endShardingKey = shardingKey.upperEndpoint();

        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        Date start = simpleDateFormat.parse(startShardingKey);
        Date end = simpleDateFormat.parse(endShardingKey);
        List<String> rangeDate = new DateUtils().getDateStringWithRange(start, end, "yyyyMMdd");
        for (String tableName : rangeDate) {
            result.add(logicTableName+"_"+tableName);
        }
        return result;
    }
}